<template>
  <div class="course-admin">
    <h3 class="section-title">课程管理</h3>

    <!-- 课程列表 -->
    <el-table :data="courses" style="width: 100%">
      <el-table-column prop="id" label="课程ID" width="80" />
      <el-table-column prop="name" label="课程名称" />
      <el-table-column label="开始时间">
        <template #default="scope">{{ formatDate(scope.row.start_time) }}</template>
      </el-table-column>
      <el-table-column label="结束时间">
        <template #default="scope">{{ formatDate(scope.row.end_time) }}</template>
      </el-table-column>
      <el-table-column prop="coach_name" label="负责教练" />
      <el-table-column prop="campus_name" label="校区" />
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button size="small" @click="editCourse(scope.row)">编辑</el-button>
          <el-button size="small" @click="assignCoach(scope.row)">分配教练</el-button>
          <el-button size="small" type="danger" @click="deleteCourse(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" class="mt-16" @click="addCourse">新增课程</el-button>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" label-width="100px">
        <el-form-item label="课程名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="form.start_time" type="datetime" format="YYYY-MM-DD HH:mm" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="form.end_time" type="datetime" format="YYYY-MM-DD HH:mm" />
        </el-form-item>
        <el-form-item label="负责教练">
          <el-select v-model="form.coach_id" placeholder="可选" clearable>
            <el-option v-for="c in coachOptions" :key="c.id" :label="c.real_name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="校区">
          <el-select v-model="form.campus_id" placeholder="请选择校区">
            <el-option v-for="c in campusOptions" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCourse">保存</el-button>
      </template>
    </el-dialog>

    <!-- 分配教练对话框 -->
    <el-dialog v-model="assignDialogVisible" title="分配教练">
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="课程">
          <el-input :value="assignForm.name" disabled />
        </el-form-item>
        <el-form-item label="负责教练">
          <el-select v-model="assignForm.coach_id" placeholder="可选" clearable>
            <el-option v-for="c in coachOptions" :key="c.id" :label="c.real_name" :value="c.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAssign">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'
import { Plus } from '@element-plus/icons-vue'

const authStore = useAuthStore()
const user = computed(() => authStore.user)              // 当前登录管理员（用于校区过滤）

const courses = ref([])              // 课程列表（已过滤）
const coachOptions = ref([])         // 教练下拉（已过滤）

const dialogVisible = ref(false)
const dialogTitle = computed(() => (currentId.value ? '编辑课程' : '新增课程'))
const currentId = ref(null)

const form = ref({
  name: '',
  start_time: '',
  end_time: '',
  coach_id: '',
  campus_id: ''
})

const assignDialogVisible = ref(false)
const assignForm = ref({
  id: '',
  name: '',
  coach_id: ''
})

/* ---------- 生命周期 ---------- */
onMounted(() => {
  fetchCourses()
  fetchCoachOptions()
})

/* ---------- 数据获取 ---------- */
const fetchCourses = async () => {
  // 超级管理员看全部，普通管理员只看自己校区
  const params = user.value.isSuperAdmin ? {} : { campusId: user.value.campus.id }
  const res = await request.get('/course/list-with-coach', { params })
  if (res.code === 200) courses.value = res.data
}

const fetchCoachOptions = async () => {
  // 超级管理员看全部教练，普通管理员只看自己校区教练
  const params = user.value.isSuperAdmin ? {} : { campusId: user.value.campus.id }
  const res = await request.get('/coach/options', { params })
  if (res.code === 200) coachOptions.value = res.data
}

/* ---------- 增删改 ---------- */
const addCourse = () => {
  currentId.value = null
  form.value = {
    name: '',
    start_time: '',
    end_time: '',
    coach_id: '',
    campus_id: user.value.isSuperAdmin ? '' : user.value.campus.id
  }
  dialogVisible.value = true
}

const editCourse = (row) => {
  currentId.value = row.id
  form.value = { ...row }
  dialogVisible.value = true
}

const saveCourse = async () => {
  // 时间重叠校验（后端接口需支持）
  const overlapRes = await request.post('/course/check-overlap', {
    id: currentId.value,
    start_time: form.value.start_time,
    end_time: form.value.end_time,
    campus_id: form.value.campus_id
  })
  if (overlapRes.code !== 200) {
    ElMessage.error(overlapRes.message || '时间重叠，请调整')
    return
  }

  if (currentId.value) {
    await request.put(`/course/update/${currentId.value}`, form.value)
    ElMessage.success('课程保存成功')
  } else {
    await request.post('/course/add', form.value)
    ElMessage.success('课程添加成功')
  }
  dialogVisible.value = false
  await fetchCourses()
}

const deleteCourse = async (id) => {
  await ElMessageBox.confirm('确定删除该课程？', '提示', { type: 'warning' })
  await request.delete(`/course/delete/${id}`)
  ElMessage.success('课程删除成功')
  await fetchCourses()
}

/* ---------- 分配教练 ---------- */
const assignCoach = (row) => {
  assignForm.value = { id: row.id, name: row.name, coach_id: row.coach_id || '' }
  assignDialogVisible.value = true
}

const saveAssign = async () => {
  // 时间重叠校验（后端接口需支持）
  const overlapRes = await request.post('/course/check-overlap', {
    id: assignForm.value.id,
    coach_id: assignForm.value.coach_id,
    campus_id: user.value.campus.id
  })
  if (overlapRes.code !== 200) {
    ElMessage.error(overlapRes.message || '该教练在此时间段已有课程，请调整')
    return
  }

  await request.put(`/course/assign-coach/${assignForm.value.id}`, {
    coach_id: assignForm.value.coach_id
  })
  ElMessage.success('教练分配成功')
  assignDialogVisible.value = false
  await fetchCourses()
}

/* ---------- 工具 ---------- */
const formatDate = (dt) => {
  if (!dt) return ''
  const d = new Date(dt)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}
</script>

<style scoped>
.course-admin {
  padding: 24px;
}
.section-title {
  margin: 0 0 16px;
  font-size: 18px;
  color: var(--el-color-primary);
}
.mt-16 {
  margin-top: 16px;
}
</style>